/**
 * Copyright 2013 Douglas Lacher
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Douglas Lacher <doug.lacher@gmail.com>
 */

package com.devioustoast.andmoco;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Fragment representing the user interface to calibrate servos.
 */
public class CalibrationFragment extends Fragment {

  public static final String LOG_TAG = "CalibrationFragment";
  public static final int SERVO_COUNT = 32;
  private Robot mRobot = null;

  public CalibrationFragment() {}

  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View calibrationView = inflater.inflate(R.layout.fragment_calibration, container, false);
    LinearLayout calibrationContainer = (LinearLayout) calibrationView.findViewById(
        R.id.calibration_container);

    if (mRobot != null) {
      for (int i = 0; i < SERVO_COUNT; i++) {
        final View listItemView = inflater.inflate(R.layout.calibration_list_item, container, false);
        final int servoIndex = i;
        final LinearLayout calibrationListItem = (LinearLayout) listItemView.findViewById(
            R.id.calibration_list_item);

        final TextView label = (TextView) calibrationListItem.findViewById(
            R.id.calibration_servo_label);
        label.setText(String.format("Servo %s:", servoIndex));

        final EditText input = (EditText) calibrationListItem.findViewById(
            R.id.calibration_servo_input);
        input.setText(
            String.valueOf(mRobot.getServoMap().get(servoIndex).getOffset()),
            TextView.BufferType.EDITABLE);
        input.addTextChangedListener(new OffsetTextWatcher(mRobot.getServoMap().get(servoIndex)));
        calibrationContainer.addView(calibrationListItem, servoIndex);
      }
    }
    return calibrationView;
  }

  @Override
  public void onPause() {
    if (mRobot != null) {
      mRobot.saveOffsetMap();
    }
    super.onPause();
  }

  public void setRobot(Robot robot) {
    mRobot = robot;
  }

  /**
   * A TextWatcher that handles changes to the servo's offsets.
   *
   * @author Douglas Lacher <doug.lacher@gmail.com>
   */
  public class OffsetTextWatcher implements TextWatcher {

    private Servo mServo;

    public OffsetTextWatcher(final Servo servo) {
      mServo = servo;
    }

    @Override
    public void afterTextChanged(Editable editable) {
      String offsetString = editable.toString();
      int newOffset = 0;
      if (!offsetString.isEmpty()) {
        try {
          newOffset = Integer.valueOf(editable.toString());
        } catch (NumberFormatException e) {
          // Invalid user input.  Ignore it.
        }
      }
      mServo.setOffset(newOffset);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}
  }
}
